package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.comon.CustomException;
import com.itheima.reggie.comon.JwtUtil;
import com.itheima.reggie.comon.ResultInfo;
import com.itheima.reggie.domain.User;
import com.itheima.reggie.mapper.UserMapper;
import com.itheima.reggie.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 七安
 * @description 针对表【user(用户信息)】的数据库操作Service实现
 * @createDate 2022-08-15 16:15:31
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    //获取验证码
    @Override
    public void setCode(User user) {
        //生成验证码(有钱了 用阿里云发送)
        String code = "123456";
        //将验证码添加到redis中
        redisTemplate.opsForValue().set("CODE_" + user.getPhone(), code, 5, TimeUnit.MINUTES);

    }

    //登陆
    @Override
    public ResultInfo<String> login(String phone, String code) {
        //根绝手机号进行查询
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.isNotEmpty(phone), User::getPhone, phone);
        User oldUser = userMapper.selectOne(wrapper);
        //获取redis中的验证码
        String redisCode = (String) redisTemplate.opsForValue().get("CODE_" + phone);
        //判断验证码
        if (!StringUtils.equals(code, redisCode)) {
            throw new CustomException("验证码错误");
        }
        //如果用户不为空,判断验证码是否正确
        if (oldUser != null) {
            if (oldUser.getStatus() != 1) {
                throw new CustomException("账号已被禁用,请联系客服");
            }
        } else {
            User user = new User();
            user.setPhone(phone);
            //为用户注册
            userMapper.insert(user);
        }
        //设置token
        HashMap<Object, Object> map = new HashMap<>();
        map.put("id", oldUser.getId());
        String token = JwtUtil.createToken(map);
        //将token添加到redis中
        redisTemplate.opsForValue().set("TOKEN_" + token, oldUser, 1, TimeUnit.DAYS);
        return ResultInfo.success(token);
    }
}




